<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <el-button
          v-if="operated"
          icon="el-icon-edit-outline"
          size="mini"
          type="success"
          @click="handleComplete"
        >
          同意
        </el-button>
        <el-button
          v-if="operated"
          icon="el-icon-edit-outline"
          size="mini"
          type="success"
          @click="transferOpen=true"
        >
          转办
        </el-button>
        <el-button
          v-if="operated"
          icon="el-icon-edit-outline"
          size="mini"
          type="success"
          @click="delegateOpen=true"
        >
          委派
        </el-button>
        <el-button
          v-if="operated"
          icon="el-icon-edit-outline"
          size="mini"
          type="success"
          @click="handleAddSign('BEFORE_ADD_SIGN')"
        >
          前加签
        </el-button>
        <el-button
          v-if="operated"
          icon="el-icon-edit-outline"
          size="mini"
          type="success"
          @click="handleAddSign('AFTER_ADD_SIGN')"
        >
          后加签
        </el-button>
        <el-button
          v-if="operated"
          icon="el-icon-refresh-left"
          size="mini"
          type="warning"
          @click="handleReturn"
        >
          退回
        </el-button>
        <el-button
          v-if="operated"
          icon="el-icon-circle-close"
          size="mini"
          type="danger"
          @click="handleReject"
        >
          拒绝
        </el-button>
        <el-button style="float: right" type="primary" @click="goBack">
          返回
        </el-button>
      </div>
      <el-tabs v-model="activeName">
        <el-tab-pane label="问卷信息" name="form">
          <form-info
            ref="generateForm"
            :task-id="taskForm.taskId"
            :instance-id="taskForm.instanceId"
          />
        </el-tab-pane>
        <el-tab-pane label="流转记录" name="flowRecord">
          <div class="block m20">
            <flow-timeline :flow-record-list="flowRecordList" />
          </div>
        </el-tab-pane>
        <el-tab-pane label="流程图" name="diagramImg">
          <ProcessViewer style="height: 800px;"
                         :xml="processDiagramData.bpmnXml"
                         :finished-info="processDiagramData"
          />
          <!--                         :all-comment-list="flowTaskCommentList"-->
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!--退回流程-->
    <el-dialog
      :title="returnTitle"
      :visible.sync="returnOpen"
      width="40%"
      append-to-body
    >
      <el-alert
        title="流程将被退回到指定流程"
        type="success"
        show-icon
        :closable="false"
        class="mb20"
      />
      <el-form ref="taskForm" :model="taskForm" label-width="80px">
        <el-form-item label="退回节点" prop="targetKey">
          <el-radio-group v-model="taskForm.targetKey">
            <el-radio-button
              v-for="item in returnTaskList"
              :key="item.taskDefinitionKey"
              :label="item.taskDefinitionKey"
            >
              {{ item.name }}
            </el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="退回意见"
          prop="comment"
          :rules="[{ required: true, message: '请输入意见', trigger: 'blur' }]"
        >
          <el-input
            v-model="taskForm.comment"
            type="textarea"
            placeholder="请输入意见"
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button icon="el-icon-close" @click="returnOpen = false">取 消</el-button>
        <el-button icon="el-icon-check" type="primary" @click="taskReturn">确 定</el-button>
      </span>
    </el-dialog>
    <!--审批正常流程-->
    <el-dialog
      :title="completeTitle"
      :visible.sync="completeOpen"
      append-to-body
      width="35%"
    >
      <el-alert
        title="提交审批之后流程将进入下一个审批环境"
        type="success"
        show-icon
        :closable="false"
        class="mb20"
      />
      <el-form ref="form" label-width="80px">
        <el-form-item label="审批意见" prop="comment">
          <el-input
            v-model="taskForm.comment"
            placeholder="请输入处理意见"
            type="textarea"
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button icon="el-icon-close" @click="completeOpen = false">
          取 消</el-button>
        <el-button icon="el-icon-check" type="primary" @click="taskComplete">确 定</el-button>
      </span>
    </el-dialog>
    <!--驳回流程-->
    <el-dialog
      :title="rejectTitle"
      :visible.sync="rejectOpen"
      width="40%"
      append-to-body
    >
      <el-alert
        title="拒绝后流程将直接结束"
        type="error"
        show-icon
        :closable="false"
        class="mb20"
      />
      <el-form ref="taskForm" :model="taskForm" label-width="80px">
        <el-form-item
          label="拒绝意见"
          prop="comment"
          :rules="[{ required: true, message: '请输入意见', trigger: 'blur' }]"
        >
          <el-input
            v-model="taskForm.comment"
            type="textarea"
            placeholder="请输入意见"
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button icon="el-icon-close" @click="rejectOpen = false">取 消</el-button>
        <el-button icon="el-icon-check" type="primary" @click="taskReject">确 定</el-button>
      </span>
    </el-dialog>
    <!--转办流程-->
    <el-dialog
      title="转办"
      :visible.sync="transferOpen"
      width="40%"
      append-to-body
    >
      <el-alert
        title="任务将移交给转办人处理"
        type="error"
        show-icon
        :closable="false"
        class="mb20"
      />
      <el-form ref="taskForm" :model="taskForm" label-width="80px">
        <el-form-item
          label="办理人"
          prop="comment"
          :rules="[{ required: true, message: '请选择办理人', trigger: 'blur' }]"
        >
          <el-input
            v-model="taskForm.newAssignee"
            readonly
            placeholder="请选择办理人"
            @click.native="handleOpenUserSelect()"
          />
        </el-form-item>
        <el-form-item
          label="转办意见"
          prop="comment"
          :rules="[{ required: true, message: '请输入意见', trigger: 'blur' }]"
        >
          <el-input
            v-model="taskForm.comment"
            type="textarea"
            placeholder="请输入意见"
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button icon="el-icon-close" @click="transferOpen = false">取 消</el-button>
        <el-button icon="el-icon-check" type="primary" @click="taskTransfer">确 定</el-button>
      </span>
    </el-dialog>
    <!--    委派-->
    <el-dialog
      title="委派"
      :visible.sync="delegateOpen"
      width="40%"
      append-to-body
    >
      <el-alert
        title="由于某些原因不能处理该任务，可以把任务委派给其他用户代处理，当处理完成之后再次回到当前用户这里"
        type="error"
        show-icon
        :closable="false"
        class="mb20"
      />
      <el-form ref="taskForm" :model="taskForm" label-width="80px">
        <el-form-item
          label="办理人"
          prop="comment"
          :rules="[{ required: true, message: '请选择办理人', trigger: 'blur' }]"
        >
          <el-input
            v-model="taskForm.newAssignee"
            readonly
            placeholder="请输入意见"
            @click.native="handleOpenUserSelect()"
          />
        </el-form-item>
        <el-form-item
          label="转办意见"
          prop="comment"
          :rules="[{ required: true, message: '请输入意见', trigger: 'blur' }]"
        >
          <el-input
            v-model="taskForm.comment"
            type="textarea"
            placeholder="请输入意见"
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button icon="el-icon-close" @click="delegateOpen = false">取 消</el-button>
        <el-button icon="el-icon-check" type="primary" @click="taskDelegate">确 定</el-button>
      </span>
    </el-dialog>
    <!--    前加签-->
    <el-dialog
      title="加签"
      :visible.sync="addSignOpen"
      width="40%"
      append-to-body
    >
      <el-alert
        v-if="taskForm.addSignType==='AFTER_ADD_SIGN'"
        title="当前节点处理人，需要让其他人核对流程，其他人核对完成后，回到当前节点处理人手中，当前节点处理人处理完后进入下一节点"
        type="error"
        show-icon
        :closable="false"
        class="mb20"
      />
      <el-alert
        v-if="taskForm.addSignType==='BEFORE_ADD_SIGN'"
        title="当前节点处理人，需要让其他人核对流程，其他人核对完成后，直接进入下一节点"
        type="error"
        show-icon
        :closable="false"
        class="mb20"
      />
      <el-form ref="taskForm" :model="taskForm" label-width="80px">
        <el-form-item
          label="办理人"
          prop="comment"
          :rules="[{ required: true, message: '请选择办理人', trigger: 'blur' }]"
        >
          <el-input
            v-model="taskForm.assignees"
            readonly
            placeholder="请选择办理人"
            @click.native="handleOpenUserSelect(true)"
          />
        </el-form-item>
        <el-form-item
          label="加签意见"
          prop="comment"
          :rules="[{ required: true, message: '请输入意见', trigger: 'blur' }]"
        >
          <el-input
            v-model="taskForm.comment"
            type="textarea"
            placeholder="请输入意见"
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button icon="el-icon-close" @click="addSignOpen = false">取 消</el-button>
        <el-button icon="el-icon-check" type="primary" @click="taskAddSign">确 定</el-button>
      </span>
    </el-dialog>
    <!--    用户单选-->
    <user-choose-table ref="userChooseTable" :multiple="false" @submit="val=>{handleSelectUser(val,'newAssignee')}" />
    <!--     多选-->
    <user-choose-table ref="userMulChooseTable" @submit="val=>{handleSelectUser(val, 'assignees')}" />
  </div>
</template>

<script>
import UserChooseTable from "@/views/system/user/chooseTable"
import ProcessViewer from "../../designer/ProcessViewer"
import FlowTimeline from "./FlowTimeline"
import FormInfo from "./form"

import {
  complete,
  flowRecord,
  rejectTask,
  returnList,
  returnTask,
  delegateTask, transferTask, addSignTask, getProcessDiagramData
} from "@/api/workflow/todo"



export default {
  name: "ProcessHandle",
  components: {
    FormInfo,
    UserChooseTable,
    ProcessViewer,
    FlowTimeline
  },
  props: {},
  data() {
    return {
      // 流程图
      processDiagramData: {},
      flowRecordList: [], // 流程流转数据
      taskForm: {
        returnTaskShow: false, // 是否展示回退问卷
        delegateTaskShow: false, // 是否展示回退问卷
        defaultTaskShow: true, // 默认处理
        sendUserShow: false, // 审批用户
        comment: "", // 意见内容
        instanceId: "", // 流程实例编号
        deployId: "", // 流程定义编号
        taskId: "", // 流程任务编号
        procDefId: "", // 流程编号
        vars: {},
        targetKey: "",
        // 新的办理人
        newAssignee: "",
        addSignType: "",
        // 多个选择人
        assignees: ''
      },
      activeName: "form",
      assignee: null,
      returnTaskList: [], // 回退列表数据
      // 是否显示操作按钮
      operated: true,
      completeTitle: null,
      completeOpen: false,
      returnTitle: null,
      returnOpen: false,
      rejectOpen: false,
      rejectTitle: null,
      transferOpen: false,
      addSignOpen: false,
      delegateOpen: null
    }
  },
  computed: {},
  created() {
    this.taskForm.deployId = this.$route.query && this.$route.query.deployId
    this.taskForm.taskId = this.$route.query && this.$route.query.taskId
    this.taskForm.instanceId = this.$route.query && this.$route.query.procInsId
    this.taskForm.procDefId = this.$route.query && this.$route.query.procDefId
    this.getFlowRecordList(this.taskForm.instanceId, this.taskForm.deployId)
    this.operated = this.$route.query && this.$route.query.operated == "true"
    getProcessDiagramData({processInstanceId: this.taskForm.instanceId}).then((res) => {
      this.processDiagramData = res.data
    })
  },
  methods: {
    /** 流程流转记录 */
    getFlowRecordList(procInsId, deployId) {
      const params = {procInsId: procInsId, deployId: deployId}
      flowRecord(params)
        .then((res) => {
          this.flowRecordList = res.data.flowList
        })
        .catch((res) => {
          this.goBack()
        })
    },
    /** 审批任务选择 */
    handleComplete() {
      this.completeOpen = true
      this.completeTitle = "审批流程"
      //增加问卷默认评论
      this.taskForm.comment = "同意"
    },
    /** 审批任务 */
    taskComplete() {
      if (!this.taskForm.comment) {
        this.msgError("请输入审批意见")
        return
      }
      let data = {
        ...this.taskForm,
        values: this.$refs.generateForm.formModel,
        formDataId: this.$refs.generateForm.formDataId
      }
      complete(data).then((response) => {
        this.msgSuccess("审批完成")
        this.goBack()
      })
    },
    /** 返回页面 */
    goBack() {
      // 关闭当前标签页并返回上个页面
      this.bus.$emit("onCurrentContextmenuClick", {
        id: 1,
        path: this.$route.path
      })
      this.$router.go(-1)
    },
    /** 驳回任务 */
    handleReject() {
      this.rejectOpen = true
      this.rejectTitle = "驳回流程"
    },
    handleAddSign(type) {
      this.addSignOpen = true
      this.taskForm.addSignType = type
    },
    /** 驳回任务 */
    taskReject() {
      this.$refs["taskForm"].validate((valid) => {
        if (valid) {
          this.taskForm.formDataId = this.$refs.generateForm.formDataId
          rejectTask(this.taskForm).then((res) => {
            this.msgSuccess("审批完成")
            this.goBack()
          })
        }
      })
    },
    /** 转办 */
    taskTransfer() {
      this.$refs["taskForm"].validate((valid) => {
        if (valid) {
          this.taskForm.formDataId = this.$refs.generateForm.formDataId
          transferTask(this.taskForm).then((res) => {
            this.msgSuccess("转办成功")
            this.goBack()
          })
        }
      })
    },
    taskDelegate() {
      this.$refs["taskForm"].validate((valid) => {
        if (valid) {
          this.taskForm.formDataId = this.$refs.generateForm.formDataId
          delegateTask(this.taskForm).then((res) => {
            this.msgSuccess("委派成功")
            this.goBack()
          })
        }
      })
    },
    /** 可退回任务列表 */
    handleReturn() {
      this.returnOpen = true
      this.returnTitle = "退回流程"
      returnList(this.taskForm).then((res) => {
        this.returnTaskList = res.data
        if (res.data && res.data[0]) {
          this.taskForm.targetKey = res.data[0].taskDefinitionKey
        }
        this.taskForm.values = null
      })
    },
    /** 提交退回任务 */
    taskReturn() {
      this.$refs["taskForm"].validate((valid) => {
        if (valid) {
          returnTask(this.taskForm).then((res) => {
            this.msgSuccess("退回成功")
            this.goBack()
          })
        }
      })
    },
    /** 提交退回任务 */
    taskAddSign() {
      this.$refs["taskForm"].validate((valid) => {
        if (valid) {
          this.taskForm.assigneeList = this.taskForm.assignees.split(",")
          addSignTask(this.taskForm).then((res) => {
            this.msgSuccess("加签成功")
            this.goBack()
          })
        }
      })
    },
    handleOpenUserSelect(mul) {
      if (mul) {
        this.$refs.userMulChooseTable.showDialog([])
      } else {
        this.$refs.userChooseTable.showDialog([])
      }
    },
    handleSelectUser(val, key) {
      if (val) {
        this.taskForm[key] = val.map((item) => item.userName).join(",")
        this.$refs["taskForm"].validate((valid) => {

        })
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.test-form {
  margin: 15px auto;
  width: 800px;
  padding: 15px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both;
}

.box-card {
  width: 100%;
  margin-bottom: 20px;
}

.el-tag + .el-tag {
  margin-left: 10px;
}
</style>
